#include "widget.h"


#include <QtCore>
#include <QtGui>
#include <QtNetwork>
#include <QSoftMenuBar>
#include<QXmlInputSource>

 RSSListing::RSSListing(QWidget *parent, Qt::WindowFlags wf)
     : QWidget(parent, wf)
 {
 
     QAction* about = new QAction(tr("About mqrss"), this);
     connect(about, SIGNAL(triggered()), this, SLOT(showAbout()));
     QAction* aboutQt = new QAction(tr("About Qt"), this);
     connect(aboutQt, SIGNAL(triggered()), this, SLOT(showAboutQt()));
     QAction* quit = new QAction(tr("Quit"), this);
     connect(quit, SIGNAL(triggered()), qApp, SLOT(quit()));
     QMenu *m = QSoftMenuBar::menuFor(this);

             m->addAction(aboutQt);
             m->addAction(about);
             m->addAction(quit);

     lineEdit = new QLineEdit(this);
     lineEdit->setText("http://www.vesti.ru/vesti.rss");

     fetchButton = new QPushButton(tr("Fetch"), this);
     abortButton = new QPushButton(tr("Abort"), this);
     abortButton->setEnabled(false);

     listWidget = new QListWidget(this);
     connect(listWidget, SIGNAL(itemActivated(QListWidgetItem*)),
             this, SLOT(itemActivated(QListWidgetItem*)));
     QStringList headerLabels;
     listWidget->setFrameStyle(QFrame::NoFrame);
     listWidget->setWordWrap(true);

     connect(&http, SIGNAL(readyRead(const QHttpResponseHeader &)),
              this, SLOT(readData(const QHttpResponseHeader &)));

     connect(&http, SIGNAL(requestFinished(int, bool)),
              this, SLOT(finished(int, bool)));

     connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(fetch()));
     connect(fetchButton, SIGNAL(clicked()), this, SLOT(fetch()));
     connect(abortButton, SIGNAL(clicked()), &http, SLOT(abort()));

     QVBoxLayout *layout = new QVBoxLayout(this);
     QHBoxLayout *hboxLayout = new QHBoxLayout;

     layout->addWidget(lineEdit);
     hboxLayout->addWidget(fetchButton);
     hboxLayout->addWidget(abortButton);


     layout->addLayout(hboxLayout);
     layout->addWidget(listWidget);

     listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
     setWindowTitle(tr("mqrss"));
     resize(240,300);
 }


 void RSSListing::fetch()
 {
     lineEdit->setReadOnly(true);
     fetchButton->setEnabled(false);
     abortButton->setEnabled(true);
     listWidget->clear();

     xml.clear();

     QUrl url(lineEdit->text());
     http.setHost(url.host());
     connectionId = http.get(url.path());

/*
    QUrl url(lineEdit->text());
    QHttpRequestHeader header("GET", url.path());
    header.setValue("Host", url.host());
    http.setHost(url.host());
    connectionId = http.request(header);
    qDebug() << "request";
*/
 }

 void RSSListing::readData(const QHttpResponseHeader &resp)
 {
    qDebug() << resp.statusCode();
    
    if (resp.statusCode() != 200)
         http.abort();
     else {
         parseXml();
     }
 }

 void RSSListing::finished(int id, bool error)
 {
     if (error) {
         qWarning("Received error during HTTP fetch.");
         lineEdit->setReadOnly(false);
         abortButton->setEnabled(false);
         fetchButton->setEnabled(true);
     }
     else if (id == connectionId) {
         lineEdit->setReadOnly(false);
         abortButton->setEnabled(false);
         fetchButton->setEnabled(true);
     }
 }
 int items = 0;
 int i = 0;
 void RSSListing::parseXml()
 {
     xml.addData(http.readAll());
     while (!xml.atEnd()) {
         xml.readNext();
         if (xml.isStartElement()) {
             currentTag = xml.name().toString();
      } else if (xml.isEndElement()) {
            if (xml.name() == "item" /* && !catString.isEmpty()*/) {
              if( items < 20){
                 QPixmap pix;
                 pix.load("rss.png");
                 QListWidgetItem *pitem = new QListWidgetItem;
                 items++;
                 if(textString.isEmpty()){
                    pitem->setText(QString("%1\t%2\t%3\t%4").arg(titleString).arg(dateString).arg(catString).arg(desString));
                    pitem->setIcon(pix);
                }else{
                    pitem->setText(QString("%1\t%2\t%3\t%4").arg(titleString).arg(dateString).arg(catString).arg(textString));
                    pitem->setIcon(pix);
                }
                 if(i==0){
                    pitem->setBackgroundColor(QColor::fromRgb(100,100,100));
                    i++;
                } else {
                    pitem->setBackgroundColor(QColor::fromRgb(150,150,150));
                    i=0;
                  }

                 qDebug() << xml.text().toString();
                 listWidget->addItem(pitem);
                 textString.clear();
                 catString.clear();
                 titleString.clear();
                 desString.clear();
                 dateString.clear();
             }
                 else
                 {
                     http.abort();
                 }
             }
            }else if(xml.isCharacters() && !xml.isWhitespace()){

             if (currentTag == "category")
                 catString += xml.text().toString();
             else if (currentTag == "title")
                 titleString += xml.text().toString();
             else if (currentTag == "description")
                 desString += xml.text().toString();
             else if (currentTag == "yandex:full-text")
                 textString += xml.text().toString();
             else if (currentTag == "pubDate")
                 dateString += xml.text().toString();

             }
     }



     if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
         qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
         http.abort();
     }
 }

 void RSSListing::itemActivated(QListWidgetItem * pitem)
 {
     QString str;
     str = pitem->text();
 /*    int j, pos;
     while ((j = str.indexOf("\t", j)) != -1) {
        pos = j;
        str.replace(pos, 1, "<br/>");
        ++j;
    };

     QMessageBox::about(this, tr("News"), QString("<small>%1</small>").arg(str));
 */
     newsbrowser newsBrowser;
     newsBrowser.setModal(true);
     newsBrowser.getStr(str);
     newsBrowser.exec();
 }

 void RSSListing::showAbout()
 {
        QMessageBox::about(this, tr("About"), tr("<center><big><b>mqrss</b></big><br/>Simple RSS agregator for Qtopia<br/><small>Autor: Alexander Meshkov [admeshkov@gmail.com] 2009</small></center>"));
}

  void RSSListing::showAboutQt()
 {
        QMessageBox::aboutQt(this, tr("About Qt"));
}
